package net.guerlab.sdk.anubis.request;

import java.net.URLEncoder;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.RandomUtils;

import net.guerlab.sdk.anubis.AnubisConstants;
import net.guerlab.sdk.anubis.AnubisException;
import net.guerlab.sdk.anubis.response.AccessTokenResponse;

/**
 * AccessToken请求
 *
 * @author guer
 *
 */
public class AccessTokenRequest extends AbstractRequest<AccessTokenResponse> {

    @Override
    public void createRequestUri(
            StringBuilder builder,
            String appId,
            String secretKey) {

        String salt = String.valueOf(RandomUtils.nextInt(1000, 10000));

        builder.append(AnubisConstants.URL_GET_ACCESS_TOKEN);
        builder.append("?app_id=");
        builder.append(appId);
        builder.append("&salt=");
        builder.append(salt);
        builder.append("&signature=");
        builder.append(getAccessTokenRequestSignature(appId, secretKey, salt));
    }

    @Override
    public String requestBody() {
        return null;
    }

    private String getAccessTokenRequestSignature(
            String appId,
            String secretKey,
            String salt) {
        StringBuilder build = new StringBuilder("app_id=");

        build.append(appId);
        build.append("&salt=");
        build.append(salt);
        build.append("&secret_key=");
        build.append(secretKey);

        String urlEncodedString;
        try {
            urlEncodedString = URLEncoder.encode(build.toString(), AnubisConstants.CHARSET_UTF8);
        } catch (Exception e) {
            throw new AnubisException(e.getMessage(), e);
        }

        return DigestUtils.md5Hex(urlEncodedString);
    }

}
